Black Friday Sale Upgrade Your Home →

Use an onMount lifecycle method to fetch and render data in Svelte 3

  • Svelte provides functions that can be run at kdy moments during the component's lifecycle
  • onMount runs after a component is first rendered to the DOM.
  • In this example we use the onMount function to fetch data asynchronously and while we wait for the function to return with its data Loading text is displayed.

Use Svelte 3 stores to share data between multiple unrelated components

  • Sometimes we want to be able to share data between multiple unrelated components, in Svelte we do that with stores
  • Create a new file called store.js with the following contents:
JS
import { writable } from 'svelte/store'
export const store = writable(0)
  • You can import the store in a svelte file by adding import { store } from "./store"; and get its value by using store.subscribe() which allows you to get the value of the store
  • You can update store using store.update(n => n+1);
  • The full documentation for stores

  Previous      Next